package com.activemypc.app.components

import android.annotation.*
import android.content.*
import android.os.Build.*
import android.webkit.*
import java.lang.reflect.*

/**
 *
 * @Author mocaris
 * @Date 2025-07-21
 */
@SuppressLint("SetJavaScriptEnabled")
class AppWebView(context: Context) : WebView(context) {


    val mWebViewClient = object : WebViewClient() {
        override fun shouldOverrideUrlLoading(
            view: WebView?,
            request: WebResourceRequest?
        ): Boolean {
            return super.shouldOverrideUrlLoading(view, request)
        }
    };
    val mChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
        }
    };

    init {
        settings.useWideViewPort = true
        settings.loadWithOverviewMode = true
        settings.javaScriptEnabled = true
        settings.databaseEnabled = true
        settings.domStorageEnabled = true
        settings.textZoom = 100
        settings.cacheMode = WebSettings.LOAD_DEFAULT
        settings.builtInZoomControls = false
        settings.displayZoomControls = false
        settings.setSupportZoom(true)
        settings.allowFileAccess = true
        settings.allowContentAccess = true
        settings.allowFileAccessFromFileURLs = true
        settings.allowUniversalAccessFromFileURLs = true
        settings.layoutAlgorithm = android.webkit.WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING
        if (VERSION.SDK_INT >= VERSION_CODES.O) {
            settings.safeBrowsingEnabled = false
        }
        //跨域设置
        try {
            val clazz = settings.javaClass
            val method: Method? = clazz.getMethod(
                "setAllowFileAccessFromFileURLs", Boolean::class.javaPrimitiveType
            )
            method?.invoke(settings, true)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        try {
            val clazz = settings.javaClass
            val method: Method? = clazz.getMethod(
                "setAllowUniversalAccessFromFileURLs", Boolean::class.javaPrimitiveType
            )
            method?.invoke(settings, true)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        settings.mixedContentMode = WebSettings.MIXED_CONTENT_ALWAYS_ALLOW;
        this.webViewClient = mWebViewClient
        this.webChromeClient = mChromeClient
        this.isFocusable = true
        this.isFocusableInTouchMode = true
    }
}